//
//  SFAEditAlarmViewControllerViewController.m
//  AlarmClock
//
//  Created by Fedor Skrynnikov on 9/14/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SFAEditAlarmViewController.h"
#import "SQLiteUtil.h"
#import "Constants.h"

@interface SFAEditAlarmViewController ()

@end

@implementation SFAEditAlarmViewController

@synthesize name = _name;
@synthesize datePicker = _datePicker;
@synthesize dateTableCell =_dateTableCell;
@synthesize recurencePicker = _recurencePicker;
@synthesize scrollView = _scrollView;
@synthesize note = _note;
@synthesize addImageButton = _addImageButton;

@synthesize activeField = _activeField;
@synthesize initData = _initData;

#pragma mark - life cicle methods

- (void) dealloc{
    [_name release];
    [_dateTableCell release];
    [_datePicker release];
    [_recurencePicker release];
    [_scrollView release];
    [_note release];
    [_recurence release];
    [_addImageButton release];
    [_activeField release];
    [_initData release];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _recurence = [[NSArray alloc] initWithObjects:@"dayly", @"weekly", @"monthly", @"yearly", nil];
    
    NSDateFormatter* dateFormter = [[NSDateFormatter alloc]init];
    [dateFormter setDateFormat:DATE_FORMAT];
    //init fields if necessary 
    if (self.initData != nil) {
        [self.name setText:[self.initData objectForKey:@"name"]];
        [self.note setText:[self.initData objectForKey:@"note"]];
        
        NSDate* date = [dateFormter dateFromString:[self.initData objectForKey:@"date"]];
        [self.datePicker setDate:date];
        [[self.dateTableCell detailTextLabel] setText:[self.initData objectForKey:@"date"]];
        
        [self.recurencePicker selectRow:[_recurence indexOfObject:[self.initData objectForKey:@"recurence"]] inComponent:0 animated:YES];
    }else {
        [[self.dateTableCell detailTextLabel] setText:[dateFormter stringFromDate:[NSDate date]]];
    }
    [dateFormter release];
    
    //add observer for keyboard to adjust scroll view
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:self.view.window];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:self.view.window];
    keyboardIsSown = FALSE;
    
    self.scrollView.contentSize = self.scrollView.frame.size;
    self.scrollView.frame = self.view.frame;
    
    [self.view addSubview:self.scrollView];
    
    tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dissmissKeyboard)];
    [tap setCancelsTouchesInView:NO];
    [self.view addGestureRecognizer:tap];
    
}

- (void)viewDidUnload{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [self.view removeGestureRecognizer:tap];
    [tap release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - buttone's handlers

- (IBAction)saveButtonPressed{
    if (self.name.text == nil || [[self.name.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""] ) {
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"The name field is empty!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
        return;
    }
    if ([[self.datePicker date] compare:[NSDate date]] == NSOrderedAscending) {
        UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"Date is in the past. Do you want to save?" delegate:self cancelButtonTitle:@"NO" destructiveButtonTitle:@"YES" otherButtonTitles: nil];
        [actionSheet showInView:self.view];
        [actionSheet release];
    }else{
        [self saveAlarm];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (IBAction) addImageButtonPressed{
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"Where do you want to take a picture from?" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Choose from gallery" otherButtonTitles: @"Take a shot", nil];
    [actionSheet showInView:self.view];
    [actionSheet release];
}


- (IBAction)resetButtonPressed{
    [self.name setText:[NSString string]];
    [self.note setText:[NSString string]];
    [self.recurencePicker selectRow:0 inComponent:0 animated:YES];
    [self.datePicker setDate:[NSDate date] animated:YES];
}

- (IBAction)doneButtonePressed:(id)sender{
    [self.name resignFirstResponder];
}

#pragma mark - UIPickerViewDataSource methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [_recurence count];
}

#pragma mark - UIPickerViewDelegate methods

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [_recurence objectAtIndex:row];
}

#pragma mark - NSNotificationCenter callbacks

- (void) keyboardWillHide: (NSNotification*)n{
    NSDictionary* userInfo = [n userInfo];
    
    //get the size of the keyboard
    CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    //resize the view
    CGRect viewFrame = self.scrollView.frame;
    
    viewFrame.size.height += keyboardSize.height;
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.scrollView setFrame:viewFrame];
        [self.scrollView setContentOffset:offset animated:YES];
    }];
    keyboardIsSown = FALSE;
}

- (void) keyboardWillShow: (NSNotification*)n{
    if (keyboardIsSown) {
        return;
    }
    NSDictionary* userInfo = [n userInfo];
    
    //get the size of the keyboard
    CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    //save the current location so we can restore it
    offset = self.scrollView.contentOffset;
    
    //resize the view
    CGRect viewFrame = self.scrollView.frame;
    
    viewFrame.size.height -= keyboardSize.height;
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.scrollView setFrame:viewFrame];
        if (!CGRectContainsPoint(self.view.frame, self.activeField.frame.origin)) {
            CGPoint off = self.scrollView.contentOffset;
            off.y += keyboardSize.height;
            [self.scrollView setContentOffset:off animated:YES];
        }
    }];
    
    keyboardIsSown = TRUE;
}

- (void) dissmissKeyboard{
    [self.name resignFirstResponder];
    [self.note resignFirstResponder];
}

#pragma mark textField methods
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    self.activeField = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    self.activeField= nil;
}

#pragma mark UIActionSheetDelegate method
- (void) actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self saveAlarm];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void) saveAlarm{
    SQLiteUtil* sqlite = [[SQLiteUtil alloc] init];
    NSInteger row = [self.recurencePicker selectedRowInComponent:0];
    NSDate* date =self.datePicker.date;
    NSDateFormatter* dateFormter = [[NSDateFormatter alloc]init];
    [dateFormter setDateFormat:DATE_FORMAT];
    [sqlite insertInTable:@"alerts" Name:self.name.text Note:self.note.text Recurence:[_recurence objectAtIndex:row]  Date:[dateFormter stringFromDate:date]];
    [dateFormter release];
    [sqlite release];
}


@end
